<template>
  <a-modal
    :title='title'
    width='65%'
    :visible='visible'
    :confirmLoading='confirmLoading'
    @ok='handleOk'
    @cancel='handleCancel'
    cancelText='关闭'
  >
    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-row :gutter='11'>
          <a-col :md='24' :sm='24'>
            <div class='basicNew1'>基本信息</div>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='经销商名称'
              hasFeedback
            >
              <a-input
                :disabled='disableSubmit'
                placeholder='请输入经销商名称'
                v-decorator="['customerName',validatorRules.customerName]"

              />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='渠道类型'
              hasFeedback
            >
              <cn-dict-select-tag
                :disabled='disableSubmit'
                :options="{ value: 'dictDataCode', label: 'dictDataDesc'}"
                :triggerChange='true'
                dictCode='cust_channel'
                v-decorator="['channelType',validatorRules.channelType]"
                placeholder='请选择渠道'
                @change='channelChange'
              />
              <a-input
                type='hidden'
                placeholder='请选择渠道'
                v-decorator="['channelName']"
              />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='省/市/区'
              hasFeedback
              :required='true'
            >
              <cn-area-linkage
                @change='areaChange'
                v-model='areaLinkage'
                type='cascader'
                :disabled='disableSubmit'
                :province.sync='province'
                :city.sync='city'
                :area.sync='area'
              />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' hasFeedback label='经销商编号'>
              <a-input  v-decorator="['erpCode',validatorRules.customerName]" :disabled='disableSubmit' placeholder='请输入经销商编号' />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='详细地址'
              hasFeedback>
              <a-input placeholder='请输入详细地址'  :disabled='disableSubmit' v-decorator="['address', validatorRules.customerName]" />
            </a-form-item>
          </a-col>
<!--          <a-col :md='8' :sm='24'>-->
<!--            <a-form-item-->
<!--              :labelCol='labelCol'-->
<!--              :wrapperCol='wrapperCol'-->
<!--              label='渠道类型'-->
<!--            >-->
<!--              <cn-dict-select-tag-->
<!--                placeholder='请选择用户类型'-->
<!--                dict-code='user_type'-->
<!--                triggerChange-->
<!--                :options="{value:'dictDataCode',label:'dictDataDesc'}"-->
<!--                v-decorator="[ 'customerType', validatorRules.channelType]" />-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='层级'
              hasFeedback>
              <cn-dict-select-tag
                placeholder='请选择用户类型'
                dict-code='cust_Level'
                triggerChange
                :disabled='disableSubmit'
                :options="{value:'dictDataCode',label:'dictDataDesc'}"
                v-decorator.trim="[ 'extChar2', validatorRules.channelType]" />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='合作状态'
              hasFeedback>
              <a-select
                :disabled='disableSubmit'
                v-decorator.trim="[ 'enableStatus',validatorRules.channelType]"
                placeholder='请选择'
              >
                <a-select-option value='003'>
                  暂无合作
                </a-select-option>
                <a-select-option value='009'>
                  合作中
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='所属组织'
              hasFeedback
            >
              <j-tree-select
                :disabled='disableSubmit'
                placeholder='请选择所属组织'
                v-decorator="['orgCode',validatorRules.channelType]"
                data-type='org'
              />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='商超系统'
              >
              <a-input-search placeholder='请选择商超系统'
                              :disabled='disableSubmit'
                              v-decorator="[ 'scorgName']"
                              readOnly enter-button @search='custOrgCodeSearch("custOrgCode")' />
              <a-input type='hidden' v-decorator="[ 'scorgCode']"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='经销商级别'
              hasFeedback
            >
              <cn-dict-select-tag
                :disabled='disableSubmit'
                :options="{ value: 'dictDataCode', label: 'dictDataDesc' }"
                :triggerChange='true'
                dictCode='cust_level'
                v-decorator="['customerLevel', validatorRules.channelType]"
                placeholder='请选择经销商级别'
              />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item label='合作日期' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
              <a-date-picker showTime valueFormat='YYYY-MM-DD' format='YYYY-MM-DD'  :disabled='disableSubmit'
                             v-decorator="[ 'cooperateDate', validatorRules.customerName]" placeholder='请输入合作日期'
                             style='width:100%' />
            </a-form-item>
          </a-col>
<!--          <a-col :md='8' :sm='24'>-->
<!--            <a-form-item label='随车品揉价' :labelCol='{ xs: { span: 24 },-->
<!--          sm: { span: 7 },}' :wrapperCol='{xs: { span: 24 },-->
<!--          sm: { span: 15 },} '>-->
<!--              <a-select-->
<!--                placeholder='请选择'-->
<!--                :disabled='disableSubmit'-->
<!--                v-decorator="['kneadPrice',validatorRules.channelType]">-->
<!--                <a-select-option value='0'> 否</a-select-option>-->
<!--                <a-select-option value='1'> 是</a-select-option>-->
<!--              </a-select>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :md='24' :sm='24'>
            <div class='basicNew1'>联系人信息</div>
          </a-col>
          <div style='float: left;width: 100%;display: flex;' v-for='(item,index) in formItems' :key='index +"a"'>
            <div style='flex: 1'>
              <a-col :md='8' :sm='24'>
                <a-form-item label='联系人' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
                  <a-input placeholder='请输入终端名称'
                           :disabled='disableSubmit'
                           v-model='item.contactName' />
                </a-form-item>
              </a-col>
              <a-col :md='8' :sm='24'>
                <a-form-item label='联系方式' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
                  <a-input placeholder='请输入联系方式' v-model='item.contactPhone'  :disabled='disableSubmit' />
                </a-form-item>
              </a-col>
              <a-col :md='8' :sm='24'>
                <a-form-item label='主联系人' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
                  <a-select
                    placeholder='请选择'
                    :disabled='disableSubmit'
                    v-model='item.contactPk'>
                    <a-select-option value='0'> 否</a-select-option>
                    <a-select-option value='1'> 是</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </div>
            <div v-if='index==0&&!disableSubmit' class='addIcon' @click='addTicket'>+</div>
            <div v-if='index!=0&&!disableSubmit' class='addIcon' @click='reduceTicket(index)'>-</div>
          </div>

<!--          <a-col :md='24' :sm='24'>-->
<!--            <div class='basicNew1'>发票信息</div>-->
<!--          </a-col>-->
<!--          <a-col :md='8' :sm='24'>-->
<!--            <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='开票名称' hasFeedback>-->
<!--              <a-input placeholder='请输入开票名称' v-decorator="['billName',validatorRules.customerName]" />-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :md='8' :sm='24'>-->
<!--            <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='税号' hasFeedback>-->
<!--              <a-input placeholder='请输入税号' v-decorator="['duty',validatorRules.customerName]" />-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :md='8' :sm='24'>-->
<!--            <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='法人' hasFeedback>-->
<!--              <a-input placeholder='请输入法人' v-decorator="['legalPerson',validatorRules.customerName]" />-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :md='8' :sm='24'>-->
<!--            <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='开户银行' hasFeedback>-->
<!--              <a-input placeholder='请输入开户银行' v-decorator="['bankName',validatorRules.customerName]" />-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :md='8' :sm='24'>-->
<!--            <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='开户账号' hasFeedback>-->
<!--              <a-input placeholder='请输入开户账号' v-decorator="['bankAccount',validatorRules.customerName]" />-->
<!--            </a-form-item>-->
<!--          </a-col>-->

          <a-col :md='24' :sm='24'>
            <div class='basicNew1'>对接关系</div>
          </a-col>
          <div style='float: left;width: 100%;display: flex;' v-for='(item,index) in formItemContact' :key='index'>
            <div style='flex: 1'>
              <a-col :md='8' :sm='24'>
                <a-form-item label='负责岗位' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
                  <a-select
                    show-search
                    placeholder='请选择'
                    :filter-option='filterOption'
                    v-model='item.leadCadre'
                    :disabled='disableSubmit'
                    @change='e => userselectC(e,index)'
                  >
                    <a-select-option v-for='(v,i) in userListselect' :key='i' :value='v.positionCode'>
                      {{ v.positionName+ '/' + v.realName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md='8' :sm='24'>
                <a-form-item label='所在组织' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
                  <a-input :disabled='true' placeholder='请选择负责岗位' v-model='item.orgName' />
                  <a-input type='hidden' placeholder='请选择负责岗位' v-model='item.orgCode' />
                </a-form-item>
              </a-col>
            </div>
            <div v-if='index==0&&!disableSubmit' class='addIcon' @click='addLeadCadre'>+</div>
            <div v-if='index!=0&&!disableSubmit' class='addIcon' @click='delLeadCadre(index)'>-</div>
          </div>

        </a-row>
      </a-form>
    </a-spin>
    <proChose ref='prochoose' v-bind='modalProps' @okbro='okbropro'></proChose>
  </a-modal>
</template>

<script>
import proChose from '@comp/cn-components/ProChose'
import { httpAction, postAction } from '@/api/manage'
import { pick } from 'lodash'
import moment from 'moment'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import JAreaLinkage from '@comp/cn-form/CnAreaLinkage'
import { isMobile } from '@/utils/validate'
import { isNil } from 'lodash'
import JImageUpload from '@/components/cn-form/JImageUpload'
import UploadImage from '@/components/upload-image/UploadImage'
import Area from '@/components/utils/Area'

export default {
  name: 'dealer-modal',
  data() {
    return {
      name: '',
      disableSubmit:false,
      formItemContact: [{
        leadCadre: '',
        orgName: '',
        orgCode: ''
      }],
      itemModal2: {
        leadCadre: '',
        orgName: '',
        orgCode: ''
      },
      formItems: [
        {
          contactName: '',
          contactPhone: '',
          contactPk: ''
        }
      ],
      itemModal: {
        contactName: '',
        contactPhone: '',
        contactPk: ''
      },
      areaLinkage: '',
      province: '',
      city: '',
      area: '',
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },

      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {

        customerName: { rules: [{ required: true, message: '' }] },
        channelType: { rules: [{ required: true, message: '' }] },
        telephone: {
          rules: [
            { required: true, message: '', trigger: 'submit' },
            {
              validator: function(rule, value, callback) {
                if (!isMobile(value)) {
                  callback(new Error(''))
                }
                callback()
              }
            }
          ]
        }
      },
      url: {
        addOrUpdateUrl: window._CONFIG['domianURL'] + '/customerController/saveOrUpdateEntity',
        getuserList: window._CONFIG['domianURL'] + '/cnPositionController/findPageListByJurisdiction'
      },
      userListselect: []
    }
  },
  components: { JTreeSelect, JAreaLinkage, JImageUpload, UploadImage, proChose },
  created() {
    this.initAreaData()

  },
  methods: {
    okbropro(record, status, status2, status3) {
      console.log(record, status, status2, status3)
      if (status == 'custOrgCode') {
        this.form.setFieldsValue({
          scorgCode: record[0].superCode,
          scorgName: record[0].superName
        })
      }
    },
    custOrgCodeSearch(status) {
      this.$refs.prochoose.rowKey = 'id'
      let formconfig = [
        {
          key: 'superCode',
          label: '经销商编号'
        },
        {
          key: 'superName',
          label: '经销商名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '经销商编号',
            align: 'left',
            dataIndex: 'superCode',
            width: 120,
            ellipsis: true
          },
          {
            title: '经销商名称',
            align: 'left',
            dataIndex: 'superName',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/cnSysSuper/getSuperTypeTree',
        multiple: false,
        columW: 10
      }
      this.name = '经销商'
      this.$refs.prochoose.edit(formconfig, tableconfig, status, 'superName')
    },
    userselectC(e1, e2) {
      console.log(e1, e2)
      const dataSource = this.userListselect
      const dataSources = this.formItemContact
      const target = dataSource.find(item => item.positionCode == e1)
      const targets = dataSources[e2]
      if (targets) {
        targets.orgCode = target.orgCode
        targets.orgName = target.orgName
      }
      console.log(targets)
      this.formItemContact = dataSources
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    getUserList() {
      let that = this
      postAction(this.url.getuserList, { 'permflag': 'cust_position_jurisdiction_impl' }).then((res) => {
        if (res.success) {
          console.log(res)
          this.userListselect = res.result
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    addLeadCadre() {
      let modal = JSON.parse(JSON.stringify(this.itemModal2))
      this.formItemContact.push(modal)
      console.log(this.formItems)
    },
    delLeadCadre(index){
      this.formItemContact.splice(index,1)
    },
    addTicket() {
      let modal = JSON.parse(JSON.stringify(this.itemModal))
      this.formItems.push(modal)
      console.log(this.formItems)
    },
    reduceTicket(dex) {
      // let modal = JSON.parse(JSON.stringify(this.itemModal))
      this.formItems.splice(dex,1)
      console.log(dex)
    },
    uploadPictrue(e, e2) {
      console.log(e)
      console.log(e2)
    },
    channelChange(e, val) {
      this.$nextTick(() => {
        this.form.setFieldsValue({
          channelName: val.dictDataDesc
        })
        //时间格式化
      })
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.getUserList()
      this.form.resetFields()
      this.model = Object.assign({}, record)
      let pca = this.model.province + '/' + this.model.city + '/' + this.model.area
      this.areaLinkage = this.areaData.getAreaCodeByText(pca) || ''
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
        this.formItems = [...this.model.contactVoList]
        this.formItemContact = [...this.model.dockVoList]
        if (this.formItems.length == 0 || !this.formItems) {
          this.addTicket()
        }
        if (this.formItemContact.length == 0 || !this.formItemContact) {
          this.addLeadCadre()
        }
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.formItems= [{
          contactName: '',
          contactPhone: '',
          contactPk: ''
        }]
      this.itemModal= {
          contactName: '',
          contactPhone: '',
          contactPk: ''
      }
      this.formItemContact= [{
        leadCadre: '',
        orgName: '',
        orgCode: ''
      }]
      this.itemModal2= {
        leadCadre: '',
          orgName: '',
          orgCode: ''
      }
      this.model={}
    },
    handleOk() {
      if(this.disableSubmit){
        this.close()
        return
      }
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let method = ''
          if (!this.model.id) {
            method = 'post'
          } else {
            method = 'post'
          }
          let formData = Object.assign(this.model, values)
          formData.contactVoList = this.formItems
          formData.dockVoList = this.formItemContact

          console.log(formData)
          //时间格式化
          // formData.punchTime = formData.punchTime ? formData.punchTime.format('YYYY-MM-DD HH:mm:ss') : null;
          // formData.birthday = formData.birthday ? formData.birthday.format() : null;

          // console.log(formData)
          httpAction(this.url.addOrUpdateUrl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    areaChange(code) {
      let cities = this.areaData.getText(code, '多个值').cities
      let codes = this.areaData.getText(code, '多个值').codes
      this.model.province = cities.split('/')[0]
      this.model.city = cities.split('/')[1]
      this.model.area = cities.split('/')[2]
      this.model.provinceCode = this.dealCode(codes.split('/')[0], 2).join('')
      this.model.cityCode = this.dealCode(codes.split('/')[1], 4).join('')
      this.model.areaCode = this.dealCode(codes.split('/')[2], 6).join('')
      console.log(this.model)
    },
    // params:code:编号，count位数
    dealCode(code, count) {
      console.log(code)
      let num = code.split('')
      let codes = []
      for (let i = 0; i < count; i++) {
        codes.push(num[i])
      }
      return codes
    },
    initAreaData() {
      if (!this.areaData) {
        this.areaData = new Area()
      }
    }
  },
  computed: {
    modalProps() {
      return Object.assign({}, {
        name: this.name
      })
    }
  }
}
</script>

<style scoped>
.basicNew1 {
  padding: 8px 6px 8px 0;
  margin-bottom: 16px;
  border-bottom: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
  font-size: 16px;
  font-weight: 700;
}

.addIcon {
  margin-top: 4px;
  margin-right: 8px;
  float: right;
  cursor: pointer;
  width: 35px;
  height: 30px;
  text-align: center;
  line-height: 25px;
  background-color: #4d80be;
  color: white;
  border-radius: 50%;
  font-size: 20px;
}
</style>
